package com.ten_4_4.hiring.company.servlet;

import java.io.IOException;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import com.ten_4_4.hiring.comm.util.AppUtil;
import com.ten_4_4.hiring.comm.util.MailUtil;
import com.ten_4_4.hiring.company.dao.ApplicationDao;
import com.ten_4_4.hiring.company.dao.CompanyDao;
import com.ten_4_4.hiring.company.dao.PositionDao;
import com.ten_4_4.hiring.company.po.ApplicationPo;
import com.ten_4_4.hiring.company.po.CompanyPo;
import com.ten_4_4.hiring.company.po.PositionPo;
import com.ten_4_4.hiring.company.service.CompanyService;



/**
 * Servlet implementation class CompanyServlet
 */
public class CompanyServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	private CompanyService companyService = new CompanyService();  
	private CompanyDao companyDao = new CompanyDao();
	private String oldEmail;
	private PositionDao positionDao = new PositionDao();
	private ApplicationDao applicationDao = new ApplicationDao();
    public CompanyServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
	
	protected void doGet(HttpServletRequest request, HttpServletResponse 
			response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse 
			response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String command = request.getParameter("command");
		if ("toLoginPage".equals(command)) {
			toLoginPage(request, response);
		} else if ("login".equals(command)) {
			login(request, response);
		} else if ("toRegisterPage".equals(command)) {
			toRegisterPage(request, response);
		} else if ("toFindPasswordPage".equals(command)) {
			toFindPasswordPage(request, response);
		} else if ("sendEmail".equals(command)) {
			sendEmail(request, response);
		} else if ("toUpdatePasswordUI".equals(command)) {
			toUpdatePasswordUI(request, response);
		} else if ("updatePassword".equals(command)) {
			updatePassword(request, response);
		} else if ("register".equals(command)) {
			register(request, response);
		} else if ("goHome".equals(command)) {
			goHome(request, response);
		} else if ("main".equals(command)) {
			main (request, response);
		} else if ("show".equals(command)) {
			show (request, response);
		} else if ("update_query".equals(command)) {
			update_query(request, response);
		} else if ("update".equals(command)) {
			update(request, response);
		} else if ("logout".equals(command)) {
			logout(request, response);
		}  else {
			throw new IllegalStateException("请求非法~");
		}
	}
	
/**
 * 查询登录企业所发布的职位信息
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
//	private void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		int companyId = AppUtil.getCompanyId(request, response);
//		//int talentId = AppUtil.getTalentId(request, response);		
//		List<PositionPo> positionList = PositionDao.listById(companyId);
//		request.setAttribute("positionList", positionList);
//		
//		//List<ApplicationPo> applicationList = ApplicationDao.listById(companyId);
//		//request.setAttribute("applicationList", applicationList);
//		request.getRequestDispatcher("WEB-INF/view/company/company-homepage.jsp").forward(request, response);
//	}

	private void goHome(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("WEB-INF/view/comm/site-homepage.jsp").forward(request, response);
	}
	
	

	/**
	 * 到主页时的查询
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void main(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1、获取参数
		String rowStr = request.getParameter("row");
		// 非登录操作
		if (rowStr != null) {
			int row = Integer.parseInt(rowStr);
			if (row == 1) {
				request.setAttribute("success", "操作成功！");
			} else {
				request.setAttribute("error", "操作失败！");
			}
		}

		// 转向
		request.getRequestDispatcher(
				"ApplicationServlet?command=listCompanyVerifyByPage").forward(
				request, response);
	}
	
	
	/**
	 * 企业找回密码
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void toFindPasswordPage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("WEB-INF/view/company/company-find-password.jsp").forward(
				request, response);
	}
	
	/**
	 * 发送密码重置邮件
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void sendEmail(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String accountType = request.getParameter("accountType");
		String email = request.getParameter("email");
		//String validateCode = request.getParameter("validateCode");
//		String sessionValidateCode = (String) request.getSession()
//				.getAttribute("rand");
		// 1、验证码判断

		//if (validateCode.equals(sessionValidateCode)) {
			StringBuffer sb = new StringBuffer();
			sb.append("<p>你好 <a href=\"mailto:" + email
					+ "\" target=\"_blank\">" + email + "</a>!</p>");
			sb.append("<p>您已经请求了重置密码，可以点击下面的链接来重置密码</p>");
			sb.append("<p><a href=\"http://localhost:8080/hiring_git/CompanyServlet?command=toUpdatePasswordUI&email="
					+ email
					+ "&accountType="
					+ accountType
					+ "\" target=\"_blank\">点此链接重置密码（此链接5分钟内有效）"
					+ "</a></p>");
			sb.append("<p>如果你没有请求重置密码，请忽略这封邮件</p>");
			sb.append("<p>在你点击上面链接修改密码之前，你的密码将会保持不变。</p>");
			// 2、如果验证码正确，再执行邮件的发送

			MailUtil.send(email, "Hiring重置密码信息", sb.toString());
			request.getRequestDispatcher(
					"/WEB-INF/view/company/company-login.jsp?sentEmail=true").forward(
					request, response);
		//} else {
//			request.setAttribute("email", email);
//			toFindPasswordPage(request, response);
		}
//	}
	
	/**
	 * 转到修改密码页面
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void toUpdatePasswordUI(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		request.getRequestDispatcher("/WEB-INF/view/company/company-update-password.jsp")
				.forward(request, response);
	}
	
	/**

	 * 修改密码页面
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void updatePassword(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//String accountType = request.getParameter("accountType");
		String email = request.getParameter("email");
		String newPassword = request.getParameter("newPassword");
		//companyService.updatePassword(accountType,email, newPassword);
		companyService.updatePassword(null,email, newPassword);
		request.getRequestDispatcher("/WEB-INF/view/company/company-login.jsp").forward(
				request, response);
	}
		

	/**
	 * 企业的注册
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	private void register(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 1、获取前台传过来的参数
		String code = request.getParameter("code");
		String password = request.getParameter("password");
		String name = request.getParameter("name");	
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		String linkman = request.getParameter("linkman");
		String address = request.getParameter("address");		
		int numbers = Integer.parseInt(request.getParameter("numbers"));
		String slogan = request.getParameter("slogan");
		

		// 2、调用业务逻辑
		CompanyPo company = new CompanyPo();
		company.setCode(code);
		company.setPassword(password);
		company.setName(name);
		company.setEmail(email);
		company.setPhone(phone);	
		company.setLinkman(linkman);
		company.setAddress(address);
		company.setNumbers(numbers);
		company.setSlogan(slogan);
		companyDao.resiter(company);

		// 3、转向
		request.getRequestDispatcher("WEB-INF/view/company/company-login.jsp").forward(
				request, response);
	}

	/**
	 * 企业登录
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void login(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String code = request.getParameter("code");
		String password = request.getParameter("password");

		// 2、调用业务逻辑
		CompanyPo company = companyDao.login(code, password);
		// 3、转向
		if (company == null) {
			request.setAttribute("code", code);
			request.setAttribute("errorInfo", "用户名或密码错误！");
			request.getRequestDispatcher("WEB-INF/view/company/company-login.jsp")
					.forward(request, response);
		} else {
			request.getSession().setAttribute("company", company);
			response.sendRedirect("CompanyServlet?command=main");
		}
	}
	
	/**
	 * 企业资料显示
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void show(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 转向
		request.getRequestDispatcher("WEB-INF/view/company/company-info.jsp").forward(
				request, response);
	}
	
	/**
	 * 企业信息的修改前的查询
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
    
	private void update_query(HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		int id = Integer.parseInt(request.getParameter("id"));

		// 2、调用业务逻辑
		java.sql.Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			// 1、加载驱动
			Class.forName("com.mysql.jdbc.Driver");

			// 2、连接数据库
			connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/hiring", "root", "root");

			// 3、操作数据库
			String sql = "SELECT * FROM company WHERE id=?";
			preparedStatement = connection.prepareStatement(sql);
		
			preparedStatement.setInt(1, id);
			resultSet = preparedStatement.executeQuery();
			resultSet.next();

			// 3、决定页面转向
			request.setAttribute("resultSet", resultSet);
			request.getRequestDispatcher("WEB-INF/view/company/company-update.jsp?id=" +id).forward(
					request, response);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (resultSet != null) {
					resultSet.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if (preparedStatement != null) {
					preparedStatement.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if (connection != null) {
					connection.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 企业信息的修改
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void update(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 1、获取前台传过来的参数
		int id = Integer.parseInt(request.getParameter("id"));
		String code = request.getParameter("code");
		String password = request.getParameter("password");
		String name = request.getParameter("name");	
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		String linkman = request.getParameter("linkman");
		String address = request.getParameter("address");		
		int numbers = Integer.parseInt(request.getParameter("numbers"));
		String slogan = request.getParameter("slogan");
		

		// 2、调用业务逻辑
		CompanyPo company = new CompanyPo();
		company.setCode(code);
		company.setPassword(password);
		company.setName(name);
		company.setEmail(email);
		company.setPhone(phone);	
		company.setLinkman(linkman);
		company.setAddress(address);
		company.setNumbers(numbers);
		company.setSlogan(slogan);
		company.setId(id);
		//companyDao.update(company);

		// 3、转向
		int row = companyDao.update(company);
		if (row == 0) {
			response.sendRedirect("WEB-INF/view/company/update.jsp?result=fail");
		} else {
			request.getSession().setAttribute("company", company);
			response.sendRedirect("CompanyServlet?command=show");
		}
		
	}
	/**
	 * 企业注销
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void logout(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1、获取前台传过来的参数
		// 2、调用业务逻辑
		request.getSession().invalidate();
		// 3、转向
		request.getRequestDispatcher("WEB-INF/view/company/company-login.jsp").forward(
				request, response);
	}
	
	/**
	 * 到登录页
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void toLoginPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("WEB-INF/view/company/company-login.jsp").forward(request, response);
	}
	
	/**
	 * 到注册页
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void toRegisterPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("WEB-INF/view/company/company-register.jsp").forward(request, response);
	}
	
//	/**
//	 * 到主页时的查询
//	 * 
//	 * @param request
//	 * @param response
//	 * @throws ServletException
//	 * @throws IOException
//	 */
//	private void main(HttpServletRequest request, HttpServletResponse response)
//			throws ServletException, IOException {
//		// 1、获取参数
//		String rowStr = request.getParameter("row");
//		// 非登录操作
//		if (rowStr != null) {
//			int row = Integer.parseInt(rowStr);
//			if (row == 1) {
//				request.setAttribute("success", "操作成功！");
//			} else {
//				request.setAttribute("error", "操作失败！");
//			}
//		}
//
//		// 转向
//		request.getRequestDispatcher(
//				"ApplicationServlet?command=listCompanyVerifyByPage").forward(
//				request, response);
//	}
}

